﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Text;
using TyNetCoreBlog.Helpers;

namespace TyNetCoreBlog.Filters
{
    /// <summary>
    /// 异常处理类（服务器异常）,根据运行环境返回不同json信息
    /// </summary>
    public class JsonExceptionFilter : IExceptionFilter
    {
        private readonly IHostEnvironment _env;
        private readonly ILogger<Program> _logger;

        public JsonExceptionFilter(IHostEnvironment env,ILogger<Program> logger)
        {
            this._env = env;
            this._logger = logger;
        }


        public void OnException(ExceptionContext context)
        {
            var error = new ApiError();
            if (_env.IsDevelopment())
            {
                error.Status = StatusCodes.Status500InternalServerError;
                error.Message = context.Exception.Message;
                error.Detail = context.Exception.ToString();
            }
            else
            {
                error.Status = StatusCodes.Status500InternalServerError;
                error.Message = "服务器出错";
                error.Detail = context.Exception.Message;
            }

            context.Result = new ObjectResult(error)
            {
                StatusCode = StatusCodes.Status500InternalServerError
            };

            StringBuilder sb = new StringBuilder();
            sb.AppendLine($"服务器发生异常：{context.Exception.Message}");
            sb.AppendLine(context.Exception.ToString());
            _logger.LogCritical(sb.ToString());
        }
    }
}
